<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="400px" v-loading="loading">
    <el-upload :headers="headers" :file-list="fileList" :on-remove="onRemove" :auto-upload="true" action="/file/upload" :http-request="uploadFile" :before-upload="beforeUpload" drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="returnPolicy">确定</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      insureUrl: "",
      title: "上传发票",
      dialogFormVisible: false,
      row: {},
      file: null,
    };
  },
  methods: {
    onRemove(file) {
      this.fileList = this.fileList.filter((item) => item.name !== file.name);
    },
    close() {
      this.dialogFormVisible = false;
    },
    beforeUpload(file) {
      this.file = file;
      // if (
      //     file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png"
      // ) {
      //     this.$message.warning("请上传图片");
      //     return false;
      // }
      return true;
    },
    uploadFile() {
      this.loading = true;
      const headers = {
        "Content-Type": "multipart/form-data",
      };
      const formData = new FormData();
      formData.append("file", this.file);

      this.$post("/file/upload", formData, headers)
        .then((res) => {
            console.log(res, 'res')
          if (res.code == 200) {
            this.fileList = [
              {
                name: res.data.substring(res.data.lastIndexOf("/") + 1),
                url: res.data,
              },
            ];
          } else {
            this.fileList = [];
          }
        }).catch(() => {
            this.fileList = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    returnPolicy() {
      if (!this.fileList.length) {
        this.$message.warning("请上传文件");
        return;
      }
      if (this.loading) {
        return;
      }
      this.loading = true;
      const params = {
        orderNum: this.row.orderNum,
        invoiceUrl: this.fileList.length ? this.fileList[0].url : "",
      };
      this.$post(`/warranty/invoice/upInvoice`, params)
        .then((res) => {
          if (res && res.code == 200) {
            this.$message.success("操作成功"); // 成功提示信息
            this.dialogFormVisible = false;
            this.$emit("initTable");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style scoped lang="less"></style>